package com.stylefeng.guns.modular.flagglory.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.persistence.model.Chapter;
import com.stylefeng.guns.common.persistence.dao.ChapterMapper;
import com.stylefeng.guns.common.persistence.model.GloryUser;
import com.stylefeng.guns.common.persistence.model.ReadRecord;
import com.stylefeng.guns.common.persistence.model.Setting;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.exception.FrontException;
import com.stylefeng.guns.modular.flagglory.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-02-05
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements IChapterService {
    @Autowired
    private IBookService bookService;
    @Autowired
    private IReadRecordService readRecordService;
    @Autowired
    private ISettingService settingService;
    @Autowired
    private IGloryUserService userService;
    @Override
    public void updateRecord(Chapter chapter, Integer userId, JSONObject result) throws FrontException {
        Setting readFlagSetting = settingService.getSetting("read_flag");
        Setting maxReadSetting = settingService.getSetting("max_read");
        int readFlag = Integer.parseInt(readFlagSetting.getValue());
        int maxRead = Integer.parseInt(maxReadSetting.getValue());
        //文章点击+1
        Integer readnumber = chapter.getReadnumber();
        readnumber += 1;
        chapter.setReadnumber(readnumber);
        if (updateById(chapter)) {
            //添加阅读记录
            ReadRecord readRecord = new ReadRecord();
            readRecord.setUserid(userId);
            readRecord.setChapterid(chapter.getId());
            readRecord.setCreatetime(new Date());
            EntityWrapper<ReadRecord> entityWrapper = new EntityWrapper<>();
            entityWrapper.where("userid=" + userId).and("to_days(createtime)=to_days(now())");
            int count = readRecordService.selectCount(entityWrapper);
            if (count >= maxRead) {
                readRecord.setFlag(0);
                result.put("getFlag",0);
            } else {
                readRecord.setFlag(readFlag);
                result.put("getFlag",readFlag);
                //添加flag
                GloryUser user = userService.selectById(userId);
                user.setFlag(user.getFlag() + readFlag);
                user.updateById();
            }
            readRecord.insert();
        }
    }
}
